package com;


import com.foxinmy.weixin4j.mp.WeixinProxy;
import com.zone.weixin4j.service.WeiXin4jContextAware;
import com.zone.weixin4j.service.context.WeiXin4jContextAwareImpl;
import com.zone.weixin4j.spring.TokenGenerater;
import com.zone.weixin4j.util.AesToken;
import com.zzy.weixin.entity.Customer;
import com.zzy.weixin.repository.CustomerRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;

@SpringBootApplication
public class Application {

	private static final Logger log = LoggerFactory.getLogger(Application.class);

	public static void main(String[] args) {
        SpringApplication.run(Application.class);
	}
	@Bean
	public WeixinProxy wechat() throws Exception {
		return new WeixinProxy();
	}
	@Bean
	public WeiXin4jContextAware weiXin4jContextAware(WeixinProxy proxy) throws Exception {
		WeiXin4jContextAwareImpl contextAware = new WeiXin4jContextAwareImpl();
		contextAware.setTokenGenerater(new TokenGenerater() {
			@Override
			public List<AesToken> getAesTokens() {
				AesToken token = new AesToken(proxy.getWeixinAccount().getId(),"hellozzy",proxy.getWeixinAccount().getSecret());
				List<AesToken> result = new ArrayList<>();
				result.add(token);
				return result;
			}
		});
		contextAware.init();
		return contextAware;
	}

	@Bean
	public RestTemplate restTemplate() throws Exception {
		return new RestTemplate();
	}
	@Bean
	public CommandLineRunner demo(CustomerRepository repository) {
		return (args) -> {
			// save a couple of customers
			repository.save(new Customer("Jack", "Bauer","123","ROLE_ADMIN"));
			repository.save(new Customer("Chloe", "O'Brian","123","ROLE_ADMIN"));
			repository.save(new Customer("Kim", "Bauer","123","ROLE_ADMIN"));
			repository.save(new Customer("David", "Palmer","123","ROLE_USER"));
			repository.save(new Customer("Michelle", "Dessler","123","ROLE_ADMIN"));

			// fetch all customers
			log.info("Customers found with findAll():");
			log.info("-------------------------------");
			for (Customer customer : repository.findAll()) {
				log.info(customer.toString());
			}
			log.info("");

			// fetch customers by last name
			log.info("Customer found with findByLastName('Bauer'):");
			log.info("--------------------------------------------");
			for (Customer bauer : repository.findByLastName("Bauer")) {
				log.info(bauer.toString());
			}
			log.info("");
		};
	}

}